<template>
  <div>
    <div v-for="(item, index) in dataTemplet" :key="'list' + index" class="score-list">
      <el-row :gutter="10">
        <el-col :span="21">
          <div class="business-score" :title="item.chkitemName">
            <span>{{ item.chkitemName }}</span>
            <span class="score-input">{{ item.scoreInput }}分</span>
            <dict-tag class="m-l-sm" :options="dict.type.cq_eval_score_level" :value="item.scoreLevel" />
            <dict-tag class="m-l-sm" :options="dict.type.cq_eval_result_enum" :value="item.scoreResult" />
          </div>
        </el-col>
        <el-col :span="3">
          <el-popover v-if="item.inputMode === CQ_EVAL_INPUT_MODE.OPTION" placement="left" width="200" trigger="click" v-model="item.showOptList">
            <el-button slot="reference" size="mini" type="primary" @click="selected = []" style="margin-bottom: 10px;">添加检查项</el-button>
            <el-empty :image-size="50" v-if="!item.allSelect.length" />
            <div class="opt-list-wrap" v-else>
              <div class="opt-list">
                <div
                  class="opt-item ellipsis"
                  v-for="sitem in item.allSelect"
                  :key="sitem.chkitemCode"
                  :title="sitem.chkitemName"
                  :class="{
                    selected: item.selected.includes(sitem.chkitemCode),
                    disabled: item.children.some(schild => schild.chkitemCode === sitem.chkitemCode)
                  }"
                  @click="selectItem(sitem)"
                >
                  {{ sitem.chkitemName }}
                </div>
              </div>
              <div class="btn">
                <el-button size="mini" type="primary" :disabled="!item.selected.length" @click="addItem">添加 {{ item.selected.length }}/{{ item.allSelect.length - item.children.length }}</el-button>
              </div>
            </div>
          </el-popover>
        </el-col>
      </el-row>
      <div class="line" />
      <el-row :gutter="10">
        <el-col :span="6" v-for="(citem, cindex) in item.children" :key="'form' + citem.chkitemId">
          <div class="item">
            <div class="lable-title">
              <span><span style="color: red;">*</span>{{ citem.chkitemName }}<span class="tip">减分带负号(-)</span></span>
              <el-popconfirm v-if="citem.inputMode==CQ_EVAL_INPUT_MODE.OPTION" title="移除此检查项？" confirm-button-text="移除" @confirm="removeCheckItem(cindex)">
                <i slot="reference" class="el-icon-close btn-remove pointer" />
              </el-popconfirm>
              <el-checkbox v-else v-model="citem.noCheck" @change="noCheckChange(citem)">
                <span style="font-size: 12px;">
                  甩项
                </span>
              </el-checkbox>
            </div>
            <div class="custom-form-item el-input-group el-input-group--append">
              <el-input-number v-model="citem.scoreInput" :disabled="RESULT.THROWTERM == citem.scoreResult" placeholder="负分数,例：-7" :min="-100" :precision="2" :controls="false" :max="0" class="score-value" @input="$forceUpdate()" @change="scoreChange(citem)" />
              <div class="el-input-group__append append-unit">分</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getProTradeType } from '@/api/checkScore/projectScore'
import { CQ_EVAL_INPUT_MODE, CQ_EVAL_RDC_TYPE, CQ_EVAL_RESULT_ENUM as RESULT } from '@/utils/baseData'
import { matchingRule } from '../chkitemScore/common'
export default {
  name: 'ScoreList',
  props: {
    projectId: {
      type: String,
      default: () => ''
    }
  },
  dicts: ['cq_eval_score_level', 'cq_eval_result_enum'],
  data() {
    return {
      CQ_EVAL_INPUT_MODE,
      CQ_EVAL_RDC_TYPE,
      RESULT,
      uploading: false,
      query: {},
      selected: [],
      removeItemList: [],
      showOptList: false,
      allCheckItemList: [],
      checkItemList: [],
      businessScore: {
        scoreLevel: '',
        scoreInput: '',
        scoreResult: ''
      },
      dataAllTemplet: [],
      dataTemplet: []
    }
  },
  computed: {
    selectedCodes() {
      const list = this.checkItemList || []
      return list.map(i => i.chkitemCode)
    }
  },
  watch: {
    projectId() {
      // this.tradeFilter()
    }
  },
  created() { // 初始化
    this.query = this.$route.query
  },
  mounted() {
  },
  methods: {
    scoreChange(obj) {
      if (!/^((\-[1-9]{1}\d*)(\.\d{1,2})?|(0{1}))$/.test(obj.scoreInput)) {
        if (Number(obj.scoreInput)) {
          if (obj.scoreInput > 0) {
            this.$message({ message: '扣分项取值范围 -100 ~ 0数字。', type: 'warning', duration: 5000 })
            obj.scoreInput = null
            this.$forceUpdate()
            return
          } else {
            obj.scoreInput = parseFloat(obj.scoreInput.toFixed(2))
          }
        } else {
          obj.scoreInput = null
          this.$forceUpdate()
          return
        }
      }
      if (obj.scoreInput < -100) {
        this.$message({ message: '扣分项请输入范围 -100 ~ 0数字。', type: 'warning', duration: 5000 })
        obj.scoreInput = null
        return
      }
      this.calculateScore()
    },
    calculateScore() {
      for (let j = 0; j < this.dataTemplet.length; j++) {
        let reduceScore = 0
        const child = this.dataTemplet[j].children
        for (let i = 0; i < child.length; i++) {
          if (child[i].scoreInput) {
            reduceScore += parseFloat(child[i].scoreInput)
          }
        }
        this.dataTemplet[j].scoreInput = Math.round((100 + reduceScore) * 100) / 100
        this.dataTemplet[j].scoreLevel = matchingRule({rule: this.dataTemplet[j].levelStdd, value: this.dataTemplet[j].scoreInput, type: 'number'})
        this.dataTemplet[j].scoreResult = matchingRule({rule: this.dataTemplet[j].resultStdd, value: this.dataTemplet[j].scoreInput, type: 'number'})
      }
      this.$forceUpdate()
    },
    init (row, cfgInfo) {
      row = JSON.parse(JSON.stringify(row))
      cfgInfo = JSON.parse(JSON.stringify(cfgInfo))
      const self = this
      let parents = []
      let children = []
      if (cfgInfo.children && cfgInfo.children.length > 0) {
        parents = cfgInfo.children.filter(child => child.parentId === cfgInfo.chkitemId)
        parents.forEach(item => {
          item.allSelect = [] // 所有选项
          item.selected = [] // 已选中 待添加
          item.showOptList = false
          item.removeItems = []
          item.children = [] // 已添加项
          item.scoreInput = 100
          item.scoreLevel = 'A'
          item.scoreResult = RESULT.EXCELLENT
        })
        this.dataTemplet = JSON.parse(JSON.stringify(parents)) // 选择录入
        children = cfgInfo.children.filter(child => child.parentId !== cfgInfo.chkitemId)
        for (let i = 0; i < parents.length; i++) {
          for (let j = 0; j < children.length; j++) {
            children[j].noCheck = false
            children[j].isDelete = 0
            children[j].scoreInput = null
            if (parents[i].chkitemId === children[j].parentId) {
              parents[i].allSelect.push(children[j])
              parents[i].children.push(children[j])
            }
          }
        }
      }
      if (row) {
        handleEdit(row)
      }
      if (CQ_EVAL_INPUT_MODE.OPTION === this.businessScore.inputMode) {
        // this.checkItemList = []
        for (let i = 0; i < parents.length; i++) {
          if (row && row.scores) {
            parents[i].children = parents[i].children.filter(item => row.scores.some(scoreItem => scoreItem.chkitemScoreId === item.chkitemScoreId))
          } else {
            parents[i].children = []
          }
        }
        this.dataTemplet = parents
      } else {
        this.dataTemplet = parents
      }
      // this.tradeFilter()
      // 处理编辑初始化数据
      function handleEdit (row) {
        if (row.scores && row.scores.length > 0) {
          for (let i = 0; i < self.dataAllTemplet.length; i++) {
            for (let j = 0; j < row.scores.length; j++) {
              if (row.scores[j].chkitemCode === self.dataAllTemplet[i].chkitemCode) {
                self.dataTemplet[i].scoreInput = row.scores[j].scoreInput
                self.dataTemplet[i].scoreLevel = row.scores[j].scoreLevel
                self.dataTemplet[i].scoreResult = row.scores[j].scoreResult
                self.dataTemplet[i].chkitemScoreId = row.scores[j].chkitemScoreId
              } else {
                for (let z = 0; z < self.dataTemplet[i].children.length; z++) {
                  const child = self.dataTemplet[i].children[z]
                  if (row.scores[j].chkitemCode === child.chkitemCode) {
                    child.noCheck = row.scores[j].scoreResult === RESULT.THROWTERM
                    child.scoreInput = row.scores[j].scoreInput
                    child.scoreResult = row.scores[j].scoreResult
                    child.chkitemScoreId = row.scores[j].chkitemScoreId
                  }
                }
              }
            }
          }
        }
      }
    },
    // 操盘 过滤
    async tradeFilter () {
      if (this.projectId) {
        const response = await getProTradeType({ projectId: this.projectId }).catch(() => false)
        if (response.code === 200) {
          const tradeType = response.data
          if (!tradeType) {
            this.$message.warning('项目不属于操盘与非操盘')
          }
          this.checkItemList = this.checkItemList.filter(item => item.tradeType.split(',').some(trade => trade === tradeType))
        }
      }
    },
    getValidate() {
      let validate = false
      if (this.checkItemList.length > 0) {
        validate = this.checkItemList.every(item => (item.scoreInput || item.scoreInput === 0) || item.scoreResult === RESULT.THROWTERM)
      } else {
        validate = true
      }
      if (!validate) {
        this.$message.warning('检查项，每项必填。')
      }
      return validate
    },
    getData() {
      const scores = []
      const list = [...this.checkItemList]
      this.removeItemList.forEach(item => {
        if (!list.some(listItem => listItem.chkitemCode === item.chkitemCode) && item.chkitemScoreId) {
          list.push(item)
        }
      })
      list.forEach(item => {
        scores.push({
          chkitemCfgId: item.cfgId,
          chkitemScoreId: item.chkitemScoreId,
          versionCode: item.itemVersionCode,
          scoreInput: item.scoreInput,
          scoreResult: item.scoreResult,
          scoreType: item.scoreType,
          dataType: item.dataType,
          chkitemCode: item.chkitemCode,
          isDelete: item.isDelete
        })
      })
      this.businessScore.chkitemCfgId = this.businessScore.cfgId
      this.businessScore.versionCode = this.businessScore.itemVersionCode
      scores.push({...this.businessScore})
      return scores
    },
    noCheckChange(item) {
      if (item.noCheck) {
        item.scoreInput = ''
        item.scoreResult = RESULT.THROWTERM
      } else {
        item.scoreResult = ''
      }
      this.calculateScore()
    },
    selectItem(item) {
      const code = item.chkitemCode
      const index = item.selected.findIndex(i => i === code)
      if (index > -1) item.selected.splice(index, 1)
      else item.selected.push(code)
    },
    addItem() {
      const { allCheckItemList, selected, checkItemList } = this
      this.showOptList = false
      // const isExist = checkItemList.find(i => i.chkitemCode === selected)
      // if (isExist) return this.$message('该检查项已存在')

      const arr = allCheckItemList.filter(i => selected.includes(i.chkitemCode))
      checkItemList.push(...arr)
      this.selected = []
      this.calculateScore()
    },
    removeCheckItem(index) {
      this.checkItemList[index].isDelete = 1
      this.removeItemList.push(this.checkItemList[index])
      this.checkItemList.splice(index, 1)
      this.calculateScore()
    }
  }
}
</script>

<style scoped lang='scss'>
  $lineColor: #dddddd;
  .score-list {
    border: 1px solid $lineColor;
    border-radius: 5px;
    padding: 16px;
    margin-bottom: 10px;
  }
  .line {
    margin: 0 -16px;
    margin-bottom: 16px;
    border-bottom: 1px solid $lineColor;
    height: 1px;
  }
  .business-score {
    margin-bottom: 16px;
    .score-input {
      margin-left: 10px;
    }
    .m-l-sm {
      display: inline-block;
      margin-left: 10px;
    }
  }
  .opt-list-wrap {
    margin: 0 -12px;
    .opt-list {
      max-height: 300px;
      overflow-y: auto;
    }
    .opt-item {
      font-size: 12px;
      padding: 0 40px 0 20px;
      color: #606266;
      line-height: 34px;
      cursor: pointer;
      &:hover {
        background-color: #f5f7fa;
      }
    }
    .selected {
      color: #409eff;
      font-weight: 700;
      &::after {
        position: absolute;
        right: 20px;
        font-family: 'element-icons';
        content: '\e6da';
        font-size: 12px;
      }
    }
    .disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
    .btn {
      text-align: right;
      padding: 10px 20px 0;
    }
  }
  .item {
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(black, 0.1);
    margin-bottom: 10px;
    padding: 0 0 10px 20px;
    .lable-title {
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #ebeef5;
      padding: 10px 10px 5px;
      margin:0 0 10px -20px;
      .tip {
        margin-left: 6px;
        font-size: 12px;
        color: #999;
      }
      .btn-remove {
        padding: 3px;
        &:hover {
          color: #409eff;
        }
      }
    }
    .custom-form-item {
      margin-top: 10px;
      padding-right: 60px;
      .score-result {
        margin-right: 20px;
        flex: 1;
        text-align: right;
      }
    }
    .score-value{
      width: 140px;
    }
  }
</style>
